package cn.tedu.shoot;

import javax.swing.*;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;//定时器
import java.util.TimerTask;

public class World extends JPanel {
    public static final int WIDTH = 400;    //界面宽
    public static final int HEIGHT = 700;   //界面高
    private int set;                    //生成敌机次数
    int set1 ;                           //生成子弹计数
    int set1_1 ;                        //生成强化子弹计数

    public static final int RUNNING = 0;//运行状态
    public static final int PAUSE = 1;//暂停状态
    public static final int GAME_OVER = 2;//游戏结束状态
    private int state = RUNNING;//默认运行状态

    Sky sky = new Sky();                    //天空
    Hero hero = new Hero();                 //英雄机
    FlyingObject[] flyingObject = {};       //敌机数组
    Bullet[] bullet_1 = {};                 //子弹数组
    Bullet[] bullet_2 = {};                 //子弹数组
    Bullet[] bullet_3 = {};                 //子弹数组



    /**
     * 画页面和移动物体
     */
    public void paint(Graphics g) {
        g.drawImage(sky.inImages(), sky.x, sky.y, null); //画天空
        g.drawImage(sky.inImages(), sky.x, sky.y1, null); //画天空2
        g.drawImage(hero.inImages(), hero.x, hero.y, null); //画英雄机
        g.drawString("分数：" + hero.getScore(), 0, 670); //画分数
        g.drawString("生命：" + hero.getLife(), 300, 670);
        g.drawImage(Images.player, 0, 0, null); //画天空

        //获取每一个敌人
        for (FlyingObject f : flyingObject) { //遍历所有敌人
            g.drawImage(f.inImages(), f.x, f.y, null); //画敌人
        }
        //获取每一个子弹1
        for (Bullet b : bullet_1) { //遍历所有子弹
            g.drawImage(b.inImages(), b.x, b.y, null); //画子弹
        }
        for (Bullet b : bullet_2) { //遍历所有子弹
            g.drawImage(b.inImages(), b.x, b.y, null); //画子弹
        }
        for (Bullet b : bullet_3) { //遍历所有子弹
            g.drawImage(b.inImages(), b.x, b.y, null); //画子弹
        }
        if (state == GAME_OVER){
            g.drawImage(Images.gameover_1,0,0,null);
            g.drawImage(Images.gameover,0,0,null);
            g.drawString("看什么看！！！你死了！！！", 120, 670); //画分数
        }
        if(state == PAUSE){
            g.drawImage(Images.pause,0,0,null);
        }
    }

    /**
     * 产生敌机概率
     */
    public FlyingObject nextFlyinfObject() {
        Random random = new Random();
        int a = random.nextInt(20);
        if (a < 14) {
            return new Airplane();
        } else if (a < 19) {
            return new BigAirplane();
        } else {
            return new Bee();
        }
    }

    /**
     * 将战舰定时加入敌舰数组
     */
    public void setFlyingObject() {
        set++;
        if (set % 40 == 0) {
            FlyingObject c = nextFlyinfObject();
            flyingObject = Arrays.copyOf(flyingObject, flyingObject.length + 1);
            flyingObject[flyingObject.length - 1] = c;
        }
    }

    /**
     * 将子弹定时加入敌舰数组
     */
    public void setBullet() {
        if (hero.state == Hero.FIRE) {
            set1++;
            if (set % 30 == 0) {
                Bullet b = hero.setBullet();
                bullet_1 = Arrays.copyOf(bullet_1, bullet_1.length + 1);
                bullet_1[bullet_1.length - 1] = b;
            }
        } else {
            set1++;
            set1_1++;
            if (set % 30 == 0) {
                Bullet a = hero.setBullet();
                bullet_1 = Arrays.copyOf(bullet_1, bullet_1.length + 1);
                bullet_1[bullet_1.length - 1] = a;
                Bullet b = hero.setBullet2();
                bullet_2 = Arrays.copyOf(bullet_2, bullet_2.length + 1);
                bullet_2[bullet_2.length - 1] = b;
                Bullet c = hero.setBullet3();
                bullet_3 = Arrays.copyOf(bullet_3, bullet_3.length + 1);
                bullet_3[bullet_3.length - 1] = c;
                if (set1_1 >= 600){
                    hero.state = Hero.FIRE;
                    set1_1 = 0;
                }
            }
        }
    }

    /**
     * 所有飞行对象移动
     */
    public void stepAction() {
        for (FlyingObject object : flyingObject) {
            sky.step();
            object.step();
        }
        for (Bullet value : bullet_1) {
            value.step();
        }
        for (Bullet value : bullet_2) {
            value.step();
        }
        for (Bullet value : bullet_3) {
            value.step();
        }
        for (FlyingObject object : flyingObject) {
            object.step();
        }
    }

    /**
     * 删除越界，死亡战舰
     */
    public void getAction() {

        for (int i = 0; i < flyingObject.length; i++) {
            if (flyingObject[i].isRemove() || flyingObject[i].isOutOfBounds()) {
                flyingObject[i] = flyingObject[flyingObject.length - 1];
                flyingObject = Arrays.copyOf(flyingObject, flyingObject.length - 1);
            }
        }
        for (int i = 0; i < bullet_1.length ; i++) {
            if (bullet_1[i].isDead() || bullet_1[i].isOutOfBounds()) {
                bullet_1[i] = bullet_1[bullet_1.length - 1];
                bullet_1 = Arrays.copyOf(bullet_1, bullet_1.length - 1);

            }
        }
        for (int i = 0; i < bullet_2.length ; i++) {
            if (bullet_2[i].isDead() || bullet_2[i].isOutOfBounds()) {
                bullet_2[i] = bullet_2[bullet_2.length - 1];
                bullet_2= Arrays.copyOf(bullet_2, bullet_2.length - 1);
            }
        }
        for (int i = 0; i < bullet_3.length ; i++) {
            if (bullet_3[i].isDead() || bullet_3[i].isOutOfBounds()) {
                bullet_3[i] = bullet_3[bullet_3.length - 1];
                bullet_3 = Arrays.copyOf(bullet_3, bullet_3.length - 1);
            }
        }
    }

    /**
     * 碰撞消灭敌机子弹
     */
    public void hitAction() {
        for (FlyingObject f : flyingObject) {
            for (Bullet s : bullet_1) {
                if (f.isLive() && s.isLive() && s.isHit(f)) {
                    if (f instanceof BigAirplane){
                        ((BigAirplane) f).detLife();
                        if (((BigAirplane) f).getLife() <= 0){
                            f.goDead();
                        }
                    }else {
                        f.goDead();
                    }
                    s.goDead();
                    if(f instanceof Bee){
                        hero.state = Hero.STRENGTHEN_FIRE;
                    }
                    if (f instanceof EnemyLife && f.isDead()){
                        hero.setLife(((EnemyLife) f).enemyLife());
                    }
                    if (f instanceof EnemyScore && f.isDead()){
                        hero.setScore(((EnemyScore) f).enemyScore());
                    }
                }
            }
            for (Bullet s : bullet_2) {
                if (f.isLive() && s.isLive() && s.isHit(f)) {
                    if (f instanceof BigAirplane){
                        ((BigAirplane) f).detLife();
                        if (((BigAirplane) f).getLife() <= 0){
                            f.goDead();
                        }
                    }else {
                        f.goDead();
                    }
                    s.goDead();
                    if(f instanceof Bee){
                        hero.state = Hero.STRENGTHEN_FIRE;
                    }
                    if (f instanceof EnemyLife){
                        hero.setLife(((EnemyLife) f).enemyLife());
                    }
                    if (f instanceof EnemyScore){
                        hero.setScore(((EnemyScore) f).enemyScore());
                    }
                }
            }
            for (Bullet s : bullet_3) {
                if (f.isLive() && s.isLive() && s.isHit(f)) {
                    if (f instanceof BigAirplane){
                        ((BigAirplane) f).detLife();
                        if (((BigAirplane) f).getLife() <= 0){
                            f.goDead();
                        }
                    }else {
                        f.goDead();
                    }
                    s.goDead();
                    if(f instanceof Bee){
                        hero.state = Hero.STRENGTHEN_FIRE;
                    }
                    if (f instanceof EnemyLife){
                        hero.setLife(((EnemyLife) f).enemyLife());
                    }
                    if (f instanceof EnemyScore){
                        hero.setScore(((EnemyScore) f).enemyScore());
                    }
                }
            }
        }
    }

    /**
     * 碰撞减命
     */
    public void hitDetAction(){
        for (FlyingObject object : flyingObject) {
            if (object.isHit(hero) && object.isLive() && hero.isLive()) {
                hero.detLife();
                object.goDead();
            }
        }
    }

    /**
     * 游戏结束
     */
    public void gemaOver(){
        if (hero.getLife() <= 0){
            this.state = GAME_OVER;
        }
    }

    /**
     * 英雄机移动
     */
    public void heroMove(){
        MouseAdapter m = new MouseAdapter() {
            /*重写mouseMoved()鼠标移动事件*/
            public void mouseMoved(MouseEvent e) {
                int x = e.getX(); //获取鼠标的x坐标
                int y = e.getY(); //获取鼠标的y坐标
                if(state == RUNNING) {
                    if (x >= 1 && x <= WIDTH-1 && y <= HEIGHT-1 && y >= 1) {
                        hero.moveTo(x, y);
                    }
                }
            }
        };
        this.addMouseListener(m);
        this.addMouseMotionListener(m);

    }

    /**
     * 读取游戏存档
     */
    public void loadGame(){
        File file = new File("aircra.air");
        if(file.exists()){//判断是否存在该文件
            int r = JOptionPane.showConfirmDialog(
                    this,"是否读档?");
            if(r == JOptionPane.YES_OPTION){//如果按的确定按钮
                //加载存档
                try {
                    FileInputStream fis = new FileInputStream(file);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    SaveInfo saveInfo = (SaveInfo) ois.readObject();
                    ois.close();

                    set = saveInfo.getSet();
                    set1 = saveInfo.getSet1();
                    set1_1 = saveInfo.getSet1_1();
                    sky = saveInfo.getSky();
                    hero = saveInfo.getHero();
                    flyingObject = saveInfo.getFlyingObject();
                    bullet_1 = saveInfo.getBullet_1();
                    bullet_2 = saveInfo.getBullet_2();
                    bullet_3 = saveInfo.getBullet_3();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 写游戏存档
     */
    public void writeGame(){
        KeyAdapter k = new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_R){
                        state = PAUSE;//将游戏暂停
                    int r =JOptionPane.showConfirmDialog(World.this,"是否保存游戏");//游戏弹窗
                    if (r == JOptionPane.YES_OPTION){
                        SaveInfo saveInfo = new SaveInfo( set,  set1,  set1_1,
                         sky, hero, flyingObject, bullet_1,  bullet_2, bullet_3);//创建存档对象
                        try {
                            FileOutputStream fos = new FileOutputStream("aircra.air");//输出流
                            ObjectOutputStream oos = new ObjectOutputStream(fos);//类输出流
                            oos.writeObject(saveInfo);//将存档类写入文档
                            oos.close();//关流
                        }catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                        state = RUNNING;
                    }
                }
            }
        };
        this.addKeyListener(k);
    }

    /**
     * 游戏暂停
     */
    public void gamePause(){
        KeyAdapter k = new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_P){
                    if (state == RUNNING){
                        state = PAUSE;
                    }else if (state == PAUSE){
                        state = RUNNING;
                    }
                }
            }
        };
        this.addKeyListener(k);
    }

    /**
     * 开始
     */
    public void action() {

        Timer timer = new Timer();
        int interval = 10;//定时间隔（以毫秒为单位）1000毫秒 = 1秒
        timer.schedule(new TimerTask() {
            public void run() {
                if (state == RUNNING) {
                    setFlyingObject();//生成飞行物
                    stepAction();//移动
                    setBullet();//生成子弹
                    hitAction();//碰撞消灭子弹和敌机
                    getAction();//删除死亡战舰
                    gemaOver();//游戏结束
                    hitDetAction();//碰撞减命
                }
                repaint();
            }
        }, interval, interval);
    }

    /**
     * 主方法
     */
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        World world = new World();
        world.setFocusable(true);
        frame.add(world);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(WIDTH + 16, HEIGHT + 39);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        world.heroMove();//英雄机移动方法
        world.gamePause();//游戏暂停
        world.loadGame();
        world.writeGame();//游戏存档
        world.action();
    }

}
